<?php
	/**
	 * Created by PhpStorm.
	 * User: 陈森
	 * Date: 2020/12/22
	 * Time: 0:08
	 */

	namespace app\admin\controller\member;


	use app\admin\model\member\BuyModel;
	use core\basic\Controller;
	use core\basic\Db;
	use core\database\Mysqli;

	class MemberBuyController extends Controller
	{
		protected $model;

		public function __construct()
		{

			$this->model = new BuyModel();

		}

		public function indexJson()
		{

			if ($_GET) {
				$page = get('page') ? get('page') : 1;
				$page = intval($page);
				$limit = get('limit') ? get('limit') : 1;
				$limit = intval($limit);
				$start = $limit * ($page - 1);

				$res = $this->model->Buylist($start, $limit);

				$data = array(
					'code' => 0,
					'msg' => '',
					'count' => count($res),
					'data' => $res
				);
				return json_encode($data);
			}
		}

		public function index()
		{

			$this->display('member/BuyList.html');
		}

		public function consent()
		{
			if ($_GET) {
				$id = get('id');
				$quantity = get('quantity');
				$usermobile = get('usermobile');
				$BuyInfo = $this->model->BuyInfo(['id' => $id]);
				$userInfo = model('admin.member.Member')->checkMember(['usermobile' => $usermobile], 'id,up_integral');

				if (!$BuyInfo) {
					json(0, '操作失败');
				}
				if ($BuyInfo->status == 1) {
					try {
						$BuysetField=$this->model->BuysetField(['id' => $id],['status' => 2,'audit_time'=>get_datetime()] );
						$buysetIncd=model('admin.member.Member')->buysetInc($userInfo->id, 'up_integral',$quantity);
						if (!$buysetIncd and  !$BuysetField){
							$this->model->rollback();
							json(0, '操作失败');
						}else{
							$this->log('派送充值积分 ' . $quantity . '到' . $usermobile . '成功！');
							$UserPLog = $usermobile.'购买' . $quantity . '充值积分成功!' ;
							model('admin.member.Bill')->AddBill($userInfo->id, 3, $UserPLog, 1);
							json(1, '派送成功');
							$this->model->commit();
						}
					} catch (Exception $e) {
						$this->model->rollback();
						json(0, error());
					}
				}else{
					json(0, '已经派送过');
				}
			}
		}
		public function refuse()
		{
			if ($_GET) {
				$id = get('id');
				$quantity = get('quantity');
				$usermobile = get('usermobile');
				$BuyInfo = $this->model->BuyInfo(['id' => $id]);
				if($BuyInfo->status ==1){
					if(!!$this->model->BuysetField(['id' => $id], ['status' => 3,'audit_time'=>get_datetime()])){
						$this->log('派送充值积分 ' . $quantity . '到' . $usermobile . '审核失败！');
						json(1, ' 审核成功');
						$UserPLog = $usermobile.'购买' . $quantity . '充值积分被拒绝!' ;
						model('admin.member.Bill')->AddBill($BuyInfo->user_id, 3, $UserPLog, 1);
					}else{
						json(0, ' 审核失败');
					}
				}else{
					json(0, ' 已经审核过');
				}




			}
		}


	}